//
//  YBImManager.m
//  YBHiMo
//
//  Created by YB007 on 2021/9/15.
//  Copyright © 2021 YB007. All rights reserved.
//

#import "YBImManager.h"

#import <UserNotifications/UserNotifications.h>
#import "TUIKit.h"
//#import "TChatGroupController.h"
//#import "YBGroupInfoVC.h"
//#import "YBGroupMembersList.h"
#import "GDYLimitAlert.h"
#import <TPNS-iOS/XGPush.h>
#import <TPNS-iOS/XGPushPrivate.h>
#import "TTextMessageCell.h"
#import "TSystemMessageCell.h"
#import "TVoiceMessageCell.h"
#import "TImageMessageCell.h"
#import "TFaceMessageCell.h"
#import "TVideoMessageCell.h"
#import "TFileMessageCell.h"
#import "TGoodsCell.h"
#import "TUIKit.h"
#import "THeader.h"
#import "TUIKitConfig.h"
#import "TFaceView.h"
#import "TLocationCell.h"

@interface YBImManager()<V2TIMAdvancedMsgListener>

@property(nonatomic,assign)int imUnread;
@property(nonatomic,strong)AVPlayer *ringPlayer;


@end

@implementation YBImManager

static YBImManager *_imManager = nil;

+(instancetype)shareInstance;{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _imManager = [[super allocWithZone:NULL]init];
    });
    return _imManager;
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    return [self shareInstance];
}
#pragma mark - 登录、登出
-(void)imLogin; {
    YBWeakSelf;
    [[V2TIMManager sharedInstance] login:[Config getOwnID] userSig:[Config lgetUserSign] succ:^{
        NSLog(@"IM登录success");
        _isLogin = YES;
        //高级消息监听器
        [[V2TIMManager sharedInstance] addAdvancedMsgListener:self];
        [[XGPushTokenManager defaultTokenManager] upsertAccountsByDict:@{@(0):[Config getOwnID]}];

    } fail:^(int code, NSString *desc) {
        // 如果返回以下错误码，表示使用 UserSig 已过期，请您使用新签发的 UserSig 进行再次登录。
        // 1. ERR_USER_SIG_EXPIRED（6206）
        // 2. ERR_SVR_ACCOUNT_USERSIG_EXPIRED（70001）
        // 注意：其他的错误码，请不要在这里调用登录接口，避免 IM SDK 登录进入死循环。
        NSLog(@"IM登录失败");
        _isLogin = NO;
        [MBProgressHUD showError:YZMsg(@"IM登录失败，请重新登录")];
        [PublicObj resetUserToVisitor];
    }];
}
-(void)imLogout; {
    [[V2TIMManager sharedInstance] logout:^{
        NSLog(@"success");
        NSLog(@"退出登录成功");
        _isLogin = NO;
        [[V2TIMManager sharedInstance] removeAdvancedMsgListener:self];

    } fail:^(int code, NSString *desc) {
        NSLog(@"failure, code:%d, desc:%@", code, desc);
        NSLog(@"退出登录失败");
        _isLogin = NO;
    }];
}
//-(void)changeAppActive:(BOOL)isActive {
//    if (!isActive) {
//        TIMBackgroundParam  *param = [[TIMBackgroundParam alloc] init];
//        param.c2cUnread = self.imUnread;
//        [[TIMManager sharedInstance] doBackground:param succ:^() {
//            // to do
//            NSLog(@"rk_im_back_suc");
//        } fail:^(int code, NSString * err) {
//            // to do
//            NSLog(@"rk_im_back_fail:%d==:%@",code,err);
//        }];
//        [[UIApplication sharedApplication] setApplicationIconBadgeNumber:self.imUnread];
//    }else{
//        [[TIMManager sharedInstance] doForeground:^{
//            NSLog(@"rk_im_foreground_suc");
//        } fail:^(int code, NSString *msg) {
//            NSLog(@"rk_im_foreground_fail:%d==:%@",code,msg);
//        }];
//    }
//}

#pragma mark -  自定义消息公共方法
#pragma mark -  V2TIM 发送消息
-(void)sendV2ImMsg:(TMessageCellData *)msg andReceiver:(NSString *)receiverID complete:(ImSendV2MsgBlock)sendFinish{
    V2TIMMessage *timMsg =  [self transIMMsgFromUIMsg:msg];

    [[V2TIMManager sharedInstance]sendMessage:timMsg receiver:receiverID groupID:nil priority:V2TIM_PRIORITY_NORMAL onlineUserOnly:NO offlinePushInfo:nil progress:^(uint32_t progress) {
            
        } succ:^{
            if(sendFinish){
                sendFinish(YES,timMsg, @"发送成功");
                NSLog(@"imManagerSendTime---:%@ \n id:%@",timMsg.timestamp,timMsg.msgID);
            }
        } fail:^(int code, NSString *desc) {
            if(sendFinish){
                sendFinish(NO,timMsg, desc);
            }

        }];
}
#pragma mark -  V2TIM 发送自定义消息
-(void)sendV2CustomMsg:(V2TIMCustomElem *)customMsg andReceiver:(NSString *)receiverID complete:(ImSendV2MsgBlock)sendFinish{
    V2TIMMessage *message = [[V2TIMManager sharedInstance] createCustomMessage:customMsg.data];
    
    [[V2TIMManager sharedInstance]sendMessage:message receiver:receiverID groupID:nil priority:V2TIM_PRIORITY_NORMAL onlineUserOnly:NO offlinePushInfo:nil progress:^(uint32_t progress) {
            
        } succ:^{
            if(sendFinish){
                sendFinish(YES,message, @"发送成功");
                NSLog(@"imManagerSendTime---:%@ \n id:%@",message.timestamp,message.msgID);
            }
        } fail:^(int code, NSString *desc) {
            if(sendFinish){
                sendFinish(NO,message, desc);
            }
        }];
}
#pragma mark - 消息转换
- (V2TIMMessage *)transIMMsgFromUIMsg:(TMessageCellData *)data
{
    V2TIMMessage *msg = [[V2TIMMessage alloc] init];
    data.userHeader = [Config getUserAvatar];
    
    if([data isKindOfClass:[TTextMessageCellData class]]){
        TTextMessageCellData *text = (TTextMessageCellData *)data;
        V2TIMMessage *message = [[V2TIMManager sharedInstance] createTextMessage:text.content];
        msg = message;
    }
    else if([data isKindOfClass:[TFaceMessageCellData class]]){
        TFaceMessageCellData *image = (TFaceMessageCellData *)data;
        V2TIMMessage *message = [[V2TIMManager sharedInstance] createFaceMessage:(int)image.groupIndex data:[image.faceName dataUsingEncoding:NSUTF8StringEncoding]];
        msg = message;
    }
    else if([data isKindOfClass:[TImageMessageCellData class]]){
        TImageMessageCellData *uiImage = (TImageMessageCellData *)data;

        // 创建图片消息
        V2TIMMessage *message = [[V2TIMManager sharedInstance] createImageMessage:uiImage.path];
        msg = message;
    }
    else if([data isKindOfClass:[TVideoMessageCellData class]]){
        
        TVideoMessageCellData *uiVideo = (TVideoMessageCellData *)data;
        // 创建视频消息
        V2TIMMessage *message = [[V2TIMManager sharedInstance] createVideoMessage:uiVideo.videoPath
                                                                             type:uiVideo.videoItem.type
                                                                         duration:(int)uiVideo.videoItem.duration
                                                                     snapshotPath:uiVideo.snapshotPath];
        msg = message;
    }
    else if([data isKindOfClass:[TVoiceMessageCellData class]]){
        TVoiceMessageCellData *uiSound = (TVoiceMessageCellData *)data;
        // 创建语音消息
        V2TIMMessage *message = [[V2TIMManager sharedInstance] createSoundMessage:uiSound.path duration:uiSound.duration];
        msg = message;
    }
    else if([data isKindOfClass:[TFileMessageCellData class]]){
        TFileMessageCellData *uiFile = (TFileMessageCellData *)data;
        // 创建文件消息
        V2TIMMessage *message = [[V2TIMManager sharedInstance] createFileMessage:uiFile.path fileName:uiFile.fileName];
        msg = message;
        
    }
//    else if([data isKindOfClass:[TGiftMessageCellData class]]){
//        TIMCustomElem *imFile = [[TIMCustomElem alloc] init];
//        TGiftMessageCellData *gift = (TGiftMessageCellData *)data;
//        imFile.data = gift.data;
//
//        [msg addElem:imFile];
//    }
    else if([data isKindOfClass:[TGoodsCellData class]]){
        TGoodsCellData *imGoods = (TGoodsCellData *)data;
        V2TIMMessage *message = [[V2TIMManager sharedInstance] createCustomMessage:imGoods.data];
        msg = message;

    }

    else if ([data isKindOfClass:[TLocationCellData class]]){
        TLocationCellData *uiLocation = (TLocationCellData *)data;
        // 创建定位消息
        V2TIMMessage *message = [[V2TIMManager sharedInstance] createLocationMessage:uiLocation.locDes longitude:uiLocation.lng latitude:uiLocation.lat];
        msg = message;
    }
    return msg;
    
}

#pragma mark -  V2TIM 收到新消息//高级消息监听
-(void)onRecvNewMessage:(V2TIMMessage *)msg complete:(ImRecevNewMsgBlock)newMsg{
    NSLog(@"------wwwwww---%@",msg);

    TMessageCellData *data = nil;

    // 解析出 groupID 和 userID
        NSString *groupID = msg.groupID;
        NSString *userID = msg.userID;
        // 判断当前是单聊还是群聊：
        // 如果 groupID 不为空，表示此消息为群聊；如果 userID 不为空，表示此消息为单聊
        if (msg.status == V2TIM_MSG_STATUS_LOCAL_REVOKED) {
            if(msg.isSelf){
                TSystemMessageCellData *revoke = [[TSystemMessageCellData alloc] init];
                revoke.content = YZMsg(@"你撤回了一条消息");
                revoke.custom = msg;
                revoke.timestamp = msg.timestamp;
                data = revoke;
            }
            else{
                TSystemMessageCellData *revoke = [[TSystemMessageCellData alloc] init];
                revoke.content = YZMsg(@"对方撤回了一条消息");
                revoke.custom = msg;
                revoke.timestamp = msg.timestamp;
//                [rk_uiMsgs addObject:revoke];
                data = revoke;
            }
        }else if (msg.elemType == V2TIM_ELEM_TYPE_TEXT) {
            // 解析出 msg 中的文本消息
            V2TIMTextElem *textElem = msg.textElem;
            NSString *text = textElem.text;
            TTextMessageCellData *textData = [[TTextMessageCellData alloc] init];
            textData.content = text;
            data = textData;
            NSLog(@"onRecvNewMessage, text: %@", text);
        }else if (msg.elemType == V2TIM_ELEM_TYPE_CUSTOM) {
            // 解析出 msg 中的自定义消息
            V2TIMCustomElem *customElem = msg.customElem;
            NSData *customData = customElem.data;
            NSLog(@"onRecvNewMessage, customData: %@", customData);
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:customData options:NSJSONReadingMutableContainers error:nil];
            if ([dic valueForKey:@"method"]) {
                if ([minstr([dic valueForKey:@"method"]) isEqual:@"GoodsMsg"]) {
                    TGoodsCellData *goodsData = [[TGoodsCellData alloc]init];
                    goodsData.goodsId = minstr([dic valueForKey:@"goodsid"]);
                    data = goodsData;
                }
            }
        }else if (msg.elemType == V2TIM_ELEM_TYPE_IMAGE) {
            V2TIMImageElem *image = msg.imageElem;
            TImageMessageCellData *imageData = [[TImageMessageCellData alloc] init];
            imageData.path = image.path;
            imageData.items = [NSMutableArray array];
            for (V2TIMImage *item in image.imageList) {
                TImageItem *itemData = [[TImageItem alloc] init];
                itemData.uuid = item.uuid;
                itemData.size = CGSizeMake(item.width, item.height);
                itemData.url = item.url;
                if(item.type == V2TIM_IMAGE_TYPE_THUMB){
                    itemData.type = TImage_Type_Thumb;
                }
                else if(item.type == V2TIM_IMAGE_TYPE_LARGE){
                    itemData.type = TImage_Type_Large;
                }
                else if(item.type == V2TIM_IMAGE_TYPE_ORIGIN){
                    itemData.type = TImage_Type_Origin;
                }
                [imageData.items addObject:itemData];
            }
            data = imageData;
        }else if (msg.elemType == V2TIM_ELEM_TYPE_VIDEO) {
            //视频消息
            V2TIMVideoElem *videoElem = msg.videoElem;
            // 视频截图 ID,内部标识，可用于外部缓存 key
            NSString *snapshotUUID = videoElem.snapshotUUID;
            // 视频截图文件大小
            int snapshotSize = videoElem.snapshotSize;
            // 视频截图宽
            int snapshotWidth = videoElem.snapshotWidth;
            // 视频截图高
            int snapshotHeight = videoElem.snapshotHeight;
            // 视频 ID,内部标识，可用于外部缓存 key
            NSString *videoUUID = videoElem.videoUUID;
            // 视频文件大小
            int videoSize = videoElem.videoSize;
            // 视频时长
            int duration = videoElem.duration;
            // 设置视频截图文件路径，这里可以用 uuid 作为标识，避免重复下载
            NSString *snapshotPath = [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat: @"testVideoSnapshot%@",snapshotUUID]];
            if (![[NSFileManager defaultManager] fileExistsAtPath:snapshotPath]) {
                // 下载视频截图
                [videoElem downloadSnapshot:snapshotPath progress:^(NSInteger curSize, NSInteger totalSize) {
                    // 下载进度
                    NSLog(@"%@", [NSString stringWithFormat:@"下载视频截图进度：curSize：%lu,totalSize:%lu",curSize,totalSize]);
                } succ:^{
                    // 下载成功
                    NSLog(@"下载视频截图完成");
                } fail:^(int code, NSString *msg) {
                    // 下载失败
                    NSLog(@"%@", [NSString stringWithFormat:@"下载视频截图失败：code：%d,msg:%@",code,msg]);
                }];
            } else {
                // 视频截图已存在
            }
            NSLog(@"视频截图信息：snapshotUUID:%@, snapshotSize:%d, snapshotWidth:%d, snapshotWidth:%d, snapshotPath:%@", snapshotUUID, snapshotSize, snapshotWidth, snapshotHeight, snapshotPath);

            // 设置视频文件路径，这里可以用 uuid 作为标识，避免重复下载
            NSString *videoPath = [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat: @"testVideo%@",videoUUID]];
            if (![[NSFileManager defaultManager] fileExistsAtPath:videoPath]) {
                // 下载视频
                [videoElem downloadVideo:videoPath progress:^(NSInteger curSize, NSInteger totalSize) {
                    // 下载进度
                    NSLog(@"%@", [NSString stringWithFormat:@"下载视频进度：curSize：%lu,totalSize:%lu",curSize,totalSize]);
                } succ:^{
                    // 下载成功
                    NSLog(@"下载视频完成");
                } fail:^(int code, NSString *msg) {
                    // 下载失败
                    NSLog(@"%@", [NSString stringWithFormat:@"下载视频失败：code：%d,msg:%@",code,msg]);
                }];
            } else {
                // 视频已存在
            }
            NSLog(@"视频信息：videoUUID:%@, videoSize:%d, duration:%d, videoPath:%@", videoUUID, videoSize, duration, videoPath);
            
            TVideoMessageCellData *videoData = [[TVideoMessageCellData alloc] init];
            videoData.videoPath = videoElem.videoPath;
            videoData.snapshotPath = videoElem.snapshotPath;
            
            videoData.videoItem = [[TVideoItem alloc] init];
            videoData.videoItem.uuid = videoElem.videoUUID;
            videoData.videoItem.type = videoElem.videoType;
            videoData.videoItem.length = videoElem.videoSize;
            videoData.videoItem.duration = videoElem.duration;
            
            videoData.snapshotItem = [[TSnapshotItem alloc] init];
            videoData.snapshotItem.uuid = videoElem.snapshotUUID;
//            videoData.snapshotItem.type = videoElem.snapshot;
            videoData.snapshotItem.length = videoElem.snapshotSize;
            videoData.snapshotItem.size = CGSizeMake(videoElem.snapshotWidth, videoElem.snapshotHeight);
            data = videoData;

        }else if (msg.elemType == V2TIM_ELEM_TYPE_SOUND) {
            V2TIMSoundElem *soundElem = msg.soundElem;
            // 语音 ID,内部标识，可用于外部缓存 key
            NSString *uuid = soundElem.uuid;
            // 语音文件大小
            int dataSize = soundElem.dataSize;
            // 语音时长
            int duration = soundElem.duration;
            // 设置语音文件路径 soundPath，这里可以用 uuid 作为标识，避免重复下载
            NSString *soundPath = [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat: @"testSound%@",uuid]];
            // 判断 soundPath 下有没有已经下载过的语音文件
            if (![[NSFileManager defaultManager] fileExistsAtPath:soundPath]) {
                // 下载语音
                [soundElem downloadSound:soundPath progress:^(NSInteger curSize, NSInteger totalSize) {
                    // 下载进度
                    NSLog(@"下载语音进度：curSize：%lu,totalSize:%lu",curSize,totalSize);
                } succ:^{
                    // 下载成功
                    NSLog(@"下载语音完成");
                } fail:^(int code, NSString *msg) {
                    // 下载失败
                    NSLog(@"下载语音失败：code：%d,msg:%@",code,msg);
                }];
            } else {
                // 语音已存在
            }
            NSLog(@"语音信息：uuid:%@, dataSize:%d, duration:%d, soundPath:%@", uuid, dataSize, duration, soundPath);
            TVoiceMessageCellData *soundData = [[TVoiceMessageCellData alloc] init];
            soundData.duration = soundElem.duration;
            soundData.length = soundElem.dataSize;
            soundData.uuid = soundElem.uuid;
            data = soundData;

        }
        else if (msg.elemType == V2TIM_ELEM_TYPE_LOCATION) {
            V2TIMLocationElem *locationElem = msg.locationElem;
            // 地理位置信息描述
            NSString *desc = locationElem.desc;
            // 经度
            double longitude = locationElem.longitude;
            // 纬度
            double latitude = locationElem.latitude;
            NSLog(@"地理位置信息：desc：%@, longitude:%f, latitude:%f", desc, longitude, latitude);
            TLocationCellData *locatioData =[[TLocationCellData alloc]init];
            locatioData.lat = locationElem.latitude; //[NSString stringWithFormat:@"%f",locationElem.latitude] ;
            locatioData.lng = locationElem.longitude;//[NSString stringWithFormat:@"%f",locationElem.longitude];
            locatioData.locDes = locationElem.desc;

            data = locatioData;

        }
        else if (msg.elemType == V2TIM_ELEM_TYPE_FACE) {
            V2TIMFaceElem *faceElem = msg.faceElem;
            // 表情所在的位置
            int index = faceElem.index;
            // 表情自定义数据
            NSData *facedata = faceElem.data;
            NSLog(@"表情信息：index: %d, data: %@", index, facedata);
            
            TFaceMessageCellData *faceData = [[TFaceMessageCellData alloc] init];
            faceData.groupIndex = faceElem.index;
            faceData.faceName = [[NSString alloc] initWithData:faceElem.data encoding:NSUTF8StringEncoding];
            for (TFaceGroup *group in [[TUIKit sharedInstance] getConfig].faceGroups) {
                if(group.groupIndex == faceData.groupIndex){
                    NSString *path = [group.groupPath stringByAppendingPathComponent:faceData.faceName];
                    faceData.path = path;
                    break;
                }
            }
            data = faceData;
        }
    if(newMsg){
        [[YBImManager shareInstance] tryPlayMsgAlertWithSenderid:msg.sender];
        data.custom = msg;
        newMsg(data);
    }
}

#pragma mark - 消息已读回执通知（如果自己发的消息支持已读回执，消息接收端调用了 sendMessageReadReceipts 接口，自己会收到该回调）
-(void)onRecvMessageReadReceipts:(NSArray<V2TIMMessageReceipt *> *)receiptList{
    
}

#pragma mark - C2C 对端用户会话已读通知（如果对端用户调用 markC2CMessageAsRead 接口，自己会收到该通知）
-(void)onRecvC2CReadReceipt:(NSArray<V2TIMMessageReceipt *> *)receiptList{
    
}

#pragma mark - 收到消息撤回
-(void)onRecvMessageRevoked:(NSString *)msgID{
    
}

#pragma mark - 消息内容被修改
- (void)onRecvMessageModified:(V2TIMMessage *)msg{
    
}
#pragma mark -获取所有会话列表
-(void)getAllConversationList:(ImGetConversationListBlock)covBlock{
    [[V2TIMManager sharedInstance] getConversationList:0
                                                 count:INT_MAX
                                                  succ:^(NSArray<V2TIMConversation *> *list, uint64_t lastTS, BOOL isFinished) {
        // 获取成功，list 为会话列表
        NSMutableArray *userArr = [NSMutableArray array];
        if (isFinished) {
            
            for (V2TIMConversation *conv in list) {
                if(conv.type == V2TIM_UNKNOWN){
                    continue;
                }
                //最后一条消息
                V2TIMMessage *lastMessage = [conv lastMessage];
                
                TConversationCellData *data = [[TConversationCellData alloc] init];
                data.unRead = [conv unreadCount];;
                data.subTitle = [self getLastDisplayString:lastMessage];
                if(conv.type == V2TIM_C2C){
                    data.head = TUIKitResource(@"default_head");
                }
                else if(conv.type == V2TIM_GROUP){
                    data.head = TUIKitResource(@"default_group");
                }
                
                data.convId = conv.userID;
                NSString *timest = [NSString stringWithFormat:@"%ld", (long)[lastMessage.timestamp timeIntervalSince1970]];
                data.timestamp = timest;
                NSLog(@"获取时间错==%@",timest);
                data.convType =conv.type;
                data.title = conv.showName;
               if ([data.convId isEqual:@"admin"]) {
                    data.time = [PublicObj getDateDisplayString:lastMessage.timestamp];
                    [userArr insertObject:data atIndex:0];

                }else{
                    data.time = [PublicObj getUserDateString:lastMessage.timestamp];
                    [userArr addObject:data];
                }
            }

            if(covBlock){
                covBlock(userArr, isFinished);
            }
        }
    } fail:^(int code, NSString *msg) {
        // 获取失败
        if(covBlock){
            covBlock(@[], code);
        }

    }];

}
#pragma mark -获取不包含粉丝、赞、艾特、评论的会话列表
-(void)getConversationList:(ImGetConversationListBlock)covBlock{
    [[V2TIMManager sharedInstance] getConversationList:0
                                                 count:INT_MAX
                                                  succ:^(NSArray<V2TIMConversation *> *list, uint64_t lastTS, BOOL isFinished) {
        // 获取成功，list 为会话列表
        NSMutableArray *userArr = [NSMutableArray array];
        if (isFinished) {
            
            for (V2TIMConversation *conv in list) {
                if(conv.type == V2TIM_UNKNOWN){
                    continue;
                }
                //最后一条消息
                V2TIMMessage *lastMessage = [conv lastMessage];
                
                TConversationCellData *data = [[TConversationCellData alloc] init];
                data.unRead = [conv unreadCount];;
                data.subTitle = [self getLastDisplayString:lastMessage];
                if(conv.type == V2TIM_C2C){
                    data.head = TUIKitResource(@"default_head");
                }
                else if(conv.type == V2TIM_GROUP){
                    data.head = TUIKitResource(@"default_group");
                }
                
                data.convId = conv.userID;
                NSString *timest = [NSString stringWithFormat:@"%ld", (long)[lastMessage.timestamp timeIntervalSince1970]];
                data.timestamp = timest;
                NSLog(@"获取时间错==%@",timest);
                data.convType =conv.type;
                data.title = conv.showName;
//                if(data.convType == TConv_Type_C2C){
//                    data.title = data.convId;
//                }else if(data.convType == TConv_Type_Group){
//                    data.title = conv.showName;
//                    continue;
//                }
                //rk_顶部红点
                if ([data.convId isEqual:@"dsp_fans"]) {
                    //粉丝
                    continue;
                }else if ([data.convId isEqual:@"dsp_like"]){
                    //赞
                    continue;
                }else if ([data.convId isEqual:@"dsp_at"]){
                    //@
                    continue;
                }else if ([data.convId isEqual:@"dsp_comment"]){
                    //评论
                    continue;
                }else if ([data.convId isEqual:@"admin"]) {
                    data.time = [PublicObj getDateDisplayString:lastMessage.timestamp];
                    [userArr insertObject:data atIndex:0];

                }else{
                    data.time = [PublicObj getUserDateString:lastMessage.timestamp];
                    [userArr addObject:data];
                }
            }

            if(covBlock){
                covBlock(userArr, isFinished);
            }
        }
    } fail:^(int code, NSString *msg) {
        // 获取失败
        if(covBlock){
            covBlock(@[], code);
        }

    }];

}
#pragma mark -获取指消息未读数 除去userlist用户 userlist为空则是返回所有消息未读数
-(void)getAllUnredNumExceptUser:(NSArray *)userList complete:(ImGetUnreadBlock)finish{
    
    if ([[Config getOwnID] intValue]<0) {
        if(finish){
            finish(0);
        }
        return;
    }
    
    if(userList && userList.count > 0){
        //这个方法要主动调用
        [[V2TIMManager sharedInstance] getTotalUnreadMessageCount:^(UInt64 totalUnreadCount) {
            NSLog(@"getTotalUnreadMessageCount");
        } fail:^(int code, NSString *desc) {
        }];

        __block int unRead = 0;
        [[V2TIMManager sharedInstance]getConversationList:0 count:INT_MAX succ:^(NSArray<V2TIMConversation *> *list, uint64_t nextSeq, BOOL isFinished) {
            if(isFinished){
                // 获取成功，list 为会话列表
                NSMutableArray *userArr = [NSMutableArray arrayWithArray:list];
                
                for (V2TIMConversation *conv in list) {
                    if(conv.type == V2TIM_UNKNOWN){
                        continue;
                    }
                    for(NSString *userID in userList){
                        if ([conv.userID isEqual:userID]) {
                            [userArr removeObject:conv];
                        }
                    }
                }
                NSLog(@"immanager----userArr:%@",userArr);
                for (int i = 0; i < userArr.count; i ++) {
                    V2TIMConversation *conv = userArr[i];
                    int jjj = conv.unreadCount;
                    unRead += jjj;
                }
                if(finish){
                    finish(unRead);
                }

            }

        } fail:^(int code, NSString *desc) {
            
        }];
    }else{
        [[V2TIMManager sharedInstance] getTotalUnreadMessageCount:^(UInt64 totalCount) {
            // 获取成功，totalCount 为所有会话的未读消息总数
            // 更新 UI 上的未读数
            if(finish){
                finish((int)totalCount);
            }
        } fail:^(int code, NSString *desc) {
            // 获取失败
        }];

    }
}

#pragma mark -清空指定单聊会话的未读消息数
-(void)clearUnreadConvId:(NSString *)convid sendNot:(BOOL)send{
    [[V2TIMManager sharedInstance] markC2CMessageAsRead:convid // 待清空的单聊会话 ID
                                                   succ:^{
        // 清空成功
    } fail:^(int code, NSString *msg) {
        // 清空失败
    }];

}
#pragma mark -清空所有会话的未读消息数。
-(void)clearAllUnreadConv{
    [[V2TIMManager sharedInstance] markAllMessageAsRead:^{
        // 清空成功
        [MBProgressHUD showError:YZMsg(@"已忽略未读消息")];

    } fail:^(int code, NSString *desc) {
        // 清空失败
    }];

}
- (NSString *)getLastDisplayString:(V2TIMMessage *)lastMessage
{
    NSString *str = @"";
    if (lastMessage.status == V2TIM_MSG_STATUS_LOCAL_REVOKED) {
        if(lastMessage.isSelf){
            return YZMsg(@"你撤回了一条消息");
        }
        else{
            return [NSString stringWithFormat:@"\"%@\"%@", YZMsg(@"对方"),YZMsg(@"撤回了一条消息")];
        }
    }else if(lastMessage.elemType == V2TIM_ELEM_TYPE_TEXT){
        
        NSString *text = lastMessage.textElem.text;
        str = text;
    }else if(lastMessage.elemType == V2TIM_ELEM_TYPE_CUSTOM){
        //自定义消息
//        V2TIMCustomElem *customElem =(V2TIMCustomElem *)lastMessage;
        NSData *customData = lastMessage.customElem.data;
        
        NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:customData options:NSJSONReadingMutableLeaves error:nil];
        if([minstr([jsonDict valueForKey:@"method"]) isEqual:@"GoodsMsg"]){
            str = YZMsg(@"[商品]");
        }
//        NSLog(@"onRecvNewMessage, customData: %@ \n str:%@", customData,receiveStr);

//        str = customElem.desc;
    }else if(lastMessage.elemType == V2TIM_ELEM_TYPE_IMAGE){
        //图片消息
        str = YZMsg(@"[图片]");
    }else if(lastMessage.elemType == V2TIM_ELEM_TYPE_SOUND){
        //语音消息
        str = YZMsg(@"[语音]");
    }else if(lastMessage.elemType == V2TIM_ELEM_TYPE_VIDEO){
        //视频消息
        str = YZMsg(@"[视频]");
    }else if(lastMessage.elemType == V2TIM_ELEM_TYPE_FACE){
        //表情消息
        str = @"[动画表情]";
    }else if(lastMessage.elemType == V2TIM_ELEM_TYPE_FILE){
        //文件消息
        str = @"[文件]";
    }else if(lastMessage.elemType == V2TIM_ELEM_TYPE_LOCATION){
        //位置消息
        str = @"[位置]";
    }
    return str;
}

//-(void)pulicSendMsgWith:(NSDictionary *)msgDic receiver:(NSString *)receiverid complete:(ImStatusBlock)status;{
//    TIMConversation *conversation = [[TIMManager sharedInstance] getConversation:TIM_C2C receiver:receiverid];
//    NSData *data = [NSJSONSerialization dataWithJSONObject:msgDic options:NSJSONWritingPrettyPrinted error:nil];
//    TIMCustomElem * custom_elem = [[TIMCustomElem alloc] init];
//    [custom_elem setData:data];
//    TIMMessage * msg = [[TIMMessage alloc] init];
//    [msg addElem:custom_elem];
//
//    TIMOfflinePushInfo *pushSet = [[TIMOfflinePushInfo alloc]init];
//    pushSet.pushFlag = IM_Msg_Push;
//    [msg setOfflinePushInfo:pushSet];
//
//    [conversation sendMessage:msg succ:^(){
//        NSLog(@"SendMsg Succ:%@\n",msgDic);
//        //这里都是自己去发送自定义消息,刷新数据
//        NSArray *objA = [NSArray arrayWithObject:msg];
//        [[NSNotificationCenter defaultCenter] postNotificationName:ybImNeedRefresh object:objA userInfo:nil];
//        if (status) {
//            status(YES);
//        }
//    }fail:^(int code, NSString * err) {
//        NSLog(@"SendMsg Failed:%d->%@", code, err);
//        [MBProgressHUD showError:YZMsg(@"消息发送失败")];
//        if (status) {
//            status(NO);
//        }
//    }];
//}

/// 播放、停止响铃
-(void)playAudioCall; {
    if (_ringPlayer) {
        [_ringPlayer pause];
        _ringPlayer = nil;
    }
    NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"ring" withExtension:@"mp3"];
    _ringPlayer = [[AVPlayer alloc] initWithURL:fileURL];
    _ringPlayer.volume = 1.0;
    [_ringPlayer play];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playeyEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
}
/// 播放结束
-(void)playeyEnd:(NSNotification*)notify{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    [self playAudioCall];
}
-(void)stopAudioCall; {
    if (_ringPlayer) {
        [_ringPlayer pause];
        _ringPlayer = nil;
        [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    }
}

/// 消息提示
- (void)tryPlayMsgAlertWithSenderid:(NSString *)senderUid{
    NSString *chatUid = strFormat([[NSUserDefaults standardUserDefaults] objectForKey:ybImChatingUid]);
    BOOL iscall = [[NSUserDefaults standardUserDefaults] boolForKey:ybIsStartCallKey];
    BOOL onRoom = [[NSUserDefaults standardUserDefaults] boolForKey:ybMatchRoomCtrKey];
    if ([senderUid isEqual:chatUid] || iscall || onRoom || ![common getMsgVoiceSwitch]) {
        NSLog(@"不需要提示音");
        return;
    }
    //2020-12-17调整为用户私信不提示
    if ([senderUid containsString:@"dsp_admin_1"] ||
        [senderUid containsString:@"dsp_admin_2"] ||
        [senderUid containsString:@"dsp_fans"] ||
        [senderUid containsString:@"dsp_like"] ||
        [senderUid containsString:@"dsp_at"] ||
        [senderUid containsString:@"dsp_comment"]||
        [senderUid containsString:@"goodsorder_admin"]||
        [senderUid containsString:@"dsp_admin_control"]
        ) {
        NSURL *soundUrl = [[NSBundle mainBundle] URLForResource:@"messageVioce" withExtension:@"mp3"];
        SystemSoundID soundID;
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)soundUrl,&soundID);
        AudioServicesPlaySystemSound(soundID);
    }
}

#pragma mark - 消息处理
-(void)addNoti {
//    [self removeNoti];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onNewMessage:) name:TUIKitNotification_TIMMessageListener object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getAllUnreadNum) name:TUIKitNotification_TIMCancelunread object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getAllUnreadNum) name:TUIKitNotification_TIMRefreshListener object:nil];
}
-(void)removeNoti {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)dealloc{
    //NSLog(@"im_manager_dealloc");
    [self removeNoti];
}

//- (void)onNewMessage:(NSNotification *)notification {
////    NSLog(@"im_manager_new");
//    NSArray *msgs = notification.object;
//
//    TIMMessage *msg = [msgs lastObject];
//    for (int i = 0; i < msg.elemCount; ++i) {
//        TIMElem *elem = [msg getElem:i];
//        if([elem isKindOfClass:[TIMCustomElem class]]){
//            TIMCustomElem *custom = (TIMCustomElem *)elem;
//            NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:custom.data options:NSJSONReadingMutableContainers error:nil];
//            if ([jsonDic isKindOfClass:[NSDictionary class]] && jsonDic.count > 0) {
//                NSLog(@"收到消息------------------\n%@",jsonDic);
//                //dsp_admin_control
//                NSString *method = strFormat([jsonDic valueForKey:@"method"]);
//                // 安全风控、礼物计划-提示
//                if ([method isEqual:@"ctrl_plan"] || [method isEqual:@"gift_plan"]) {
//                    NSString *contentStr = strFormat([jsonDic valueForKey:@"title"]);
//                    if ([lagType isEqual:EN]) {
//                        contentStr = strFormat([jsonDic valueForKey:@"title_en"]);
//                    }
//                    NSDictionary *alertDic = @{
//                        @"title":YZMsg(@"提示"),
//                        @"msg":contentStr,
//                    };
//                    [GDYLimitAlert showLimitWithDic:alertDic complete:^{
//
//                    }];
//                }
//                // 试图提示
//                [[YBImManager shareInstance] tryPlayMsgAlertWithSenderid:msg.sender];
//            }
//        }
//        else if([elem isKindOfClass:[TIMGroupSystemElem class]]){
//            TIMGroupSystemElem *custom = (TIMGroupSystemElem *)elem;
//            NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:custom.userData options:NSJSONReadingMutableContainers error:nil];
//            NSLog(@"new_im_group:%@=======%ld",jsonDic,(long)custom.type);
//            if (custom.type == TIM_GROUP_SYSTEM_KICK_OFF_FROM_GROUP_TYPE ||
//                custom.type == TIM_GROUP_SYSTEM_DELETE_GROUP_TYPE) {
//                // 被踢出、被解散
//                [self userQuitOrKickDeal:custom.group];
//                [[NSNotificationCenter defaultCenter] postNotificationName:ybImConveEvent object:nil userInfo:nil];
//            }
//        }
//        else{
//            if (![elem isKindOfClass:[TIMGroupTipsElem class]]) {
//                // 试图提示
//                [[YBImManager shareInstance] tryPlayMsgAlertWithSenderid:msg.sender];
//            }
//        }
//    }
//    [self getAllUnreadNum];
//}
//-(void)userQuitOrKickDeal:(NSString *)groupId {
//    TIMConversation * convM = [[TIMManager sharedInstance] getConversation:TIM_GROUP receiver:groupId];
//    [convM setReadMessage:nil succ:^{
//    } fail:^(int code, NSString *msg) {
//    }];
//    BOOL isOK = [[TIMManager sharedInstance] deleteConversation:TIM_GROUP receiver:groupId];
//    NSLog(@"del-:%d==id:%@",isOK,groupId);
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [[NSNotificationCenter defaultCenter] postNotificationName:TUIKitNotification_TIMCancelunread object:nil];
//
////        if ([[PublicObj currentViewContorller] isKindOfClass:[TChatGroupController class]] ||
////            [[PublicObj currentViewContorller] isKindOfClass:[YBGroupInfoVC class]] ||
////            [[PublicObj currentViewContorller] isKindOfClass:[YBGroupMembersList class]]) {
////            [[YBBaseAppDelegate sharedAppDelegate] popToRootViewController];
////            //[MBProgressHUD showError:YZMsg(@"您被移出群聊")];
////        }
//    });
//}
//收到邀请展示本地推送
- (void)showLocalPush:(NSDictionary *)dic{
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
    // 标题
    content.title = YZMsg(@"通话邀请");
    content.subtitle = @"";
    // 内容
    content.body = [NSString stringWithFormat:@"%@%@%@%@",strFormat([dic valueForKey:@"user_nickname"]),YZMsg(@"向你发起"),[strFormat([dic valueForKey:@"type"]) intValue] == 1 ? YZMsg(@"视频"):YZMsg(@"语音"),YZMsg(@"通话邀请")];
    // 添加通知的标识符，可以用于移除，更新等操作
    NSString *identifier = @"noticeId";
    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:nil];
    
    [center addNotificationRequest:request withCompletionHandler:^(NSError *_Nullable error) {
        NSLog(@"成功添加推送");
    }];
    
}
//TUIKitNotification_TIMRefreshListener
//- (void)getAllUnreadNum{
////    NSLog(@"im_manager_unread");
//
//    TIMManager *manager = [TIMManager sharedInstance];
//    NSArray *convs = [manager getConversationList];
//    NSMutableArray *arrayd = [NSMutableArray array];
//    int unRead = 0;
//
//    for (int i = 0; i < convs.count; i ++) {
//        TIMConversation *conv = convs[i];
//        if([conv getType] == TIM_SYSTEM){
//            continue;
//        }else if([conv getType] == TIM_GROUP){
//            continue;
//        }else if ([[conv getReceiver] containsString:@"dsp_user_"]){
//            // dsp_user_live 【用于推送】
//            continue;
//        }
//        [arrayd addObject:conv];
//    }
//    for (int i = 0; i < arrayd.count; i ++) {
//        TIMConversation *conv = arrayd[i];
//        int jjj = [conv getUnReadMessageNum];
//        unRead += jjj;
//        NSLog(@"rk==========：%d ===:%@",jjj,[conv getReceiver]);
//    }
//    YBTabBarController *tabbar = [PublicObj currentTabbar];
//    if (!tabbar) {
//        NSLog(@"rk_==xxxx===tabbar=nil");
//        return;
//    }
//    //NSLog(@"==xxxx===tabbar=ok");
//    UITabBarItem *item = [[[tabbar tabBar] items] objectAtIndex:2];
//    //设置item角标数字
//    if (unRead == 0) {
//        item.badgeValue= nil;
//    }else{
//        item.badgeValue= [NSString stringWithFormat:@"%d",unRead];
//    }
//    self.imUnread = unRead;
//    [Config saveImUnreadNum:unRead];
//    [[NSNotificationCenter defaultCenter] postNotificationName:ybImUnreadChange object:nil userInfo:@{@"unread":@(unRead)}];
//}
#pragma mark - 获取最后一条消息

//- (void)getLastDisplayStringWith:(dispatch_group_t)imListGroup finish:(ImTransformArrayBlock)finish;{
//
//    TIMManager *manager = [TIMManager sharedInstance];
//    NSArray *convs = [manager getConversationList];
//    NSMutableArray *rk_m_array = [NSMutableArray array];
//    dispatch_queue_t group_queue = dispatch_get_global_queue(0, 0);
//    for (int i = 0; i < convs.count; i++) {
//        TIMConversation *conv = convs[i];
//        NSString *str = @"";
//        TIMMessageDraft *draft = [conv getDraft];
//        TIMMessage *msg = [conv getLastMsg];
//        //NSLog(@"rk========time:%@==im:%@",msg.timestamp,[conv getReceiver]);
//        if(draft && draft.elemCount>0){
//            TIMElem *draftElem = [draft getElem:(draft.elemCount-1)];
//            if([draftElem isKindOfClass:[TIMTextElem class]]){
//                TIMTextElem *text = (TIMTextElem *)draftElem;
//                TConversationCellData *data = [[TConversationCellData alloc] init];
//                data.subTitle = [NSString stringWithFormat:@"[%@]%@", YZMsg(@"草稿"),text.text];;
//                data.unRead = [conv getUnReadMessageNum];
//                data.lastConv = conv;
//                data.head = TUIKitResource(@"default_group");
//                data.convId = [conv getReceiver];
//                data.timestamp = msg.timestamp;
//                data.convType = (TConvType)[conv getType];
//                data.title = data.convId;  //  [conv getGroupName];
//                data.time = [PublicObj getDateDisplayString:msg.timestamp];
//                [rk_m_array addObject:data];
//            } else{
//                continue;
//            }
//            ///return str;
//        }else if(msg.status == TIM_MSG_STATUS_LOCAL_REVOKED){
//            if(msg.isSelf || [[msg getConversation] getType] == TIM_C2C){
//                //return YZMsg(@"你撤回了一条消息");
//                NSString *revokedStr = msg.isSelf ? YZMsg(@"你撤回了一条消息"):YZMsg(@"对方撤回了一条消息");
//                TConversationCellData *data = [[TConversationCellData alloc] init];
//                data.subTitle = revokedStr;
//                data.unRead = [conv getUnReadMessageNum];
//                data.lastConv = conv;
//                data.head = TUIKitResource(@"default_group");
//                data.convId = [conv getReceiver];
//                data.timestamp = msg.timestamp;
//                data.convType = (TConvType)[conv getType];
//                data.title = data.convId;  //  [conv getGroupName];
//                data.time = [PublicObj getDateDisplayString:msg.timestamp];
//                [rk_m_array addObject:data];
//            } else if([[msg getConversation] getType] == TIM_GROUP){
//                dispatch_group_enter(imListGroup);
//                dispatch_group_async(imListGroup, group_queue, ^{
//                    TIMFriendshipManager *imProfile = [TIMFriendshipManager sharedInstance];
//                    int revokedOk = [imProfile getUsersProfile:@[msg.sender] forceUpdate:YES succ:^(NSArray<TIMUserProfile *> *profiles) {
//                        TIMUserProfile * profile = [profiles lastObject];
//                        NSString *nameStr = [PublicObj transformToStringWithData:[profile.customInfo valueForKey:IMKey_Custom_Suffix_Nickname]];
//                        NSString *revokedStr = [NSString stringWithFormat:@"\"%@\"%@",nameStr,YZMsg(@"撤回了一条消息")];
//                        TConversationCellData *data = [[TConversationCellData alloc] init];
//                        data.subTitle = revokedStr;
//                        data.unRead = [conv getUnReadMessageNum];
//                        data.lastConv = conv;
//                        data.head = TUIKitResource(@"default_group");
//                        data.convId = [conv getReceiver];
//                        data.timestamp = msg.timestamp;
//                        data.convType = (TConvType)[conv getType];
//                        data.title = data.convId;
//                        data.time = [PublicObj getDateDisplayString:msg.timestamp];
//                        [rk_m_array addObject:data];
//                        dispatch_group_leave(imListGroup);
//                    } fail:^(int code, NSString *msg) {
//                        dispatch_group_leave(imListGroup);
//                    }];
//                    if (revokedOk != 0) {
//                        dispatch_group_leave(imListGroup);
//                    }
//                });
//            }else {
//                continue;
//            }
//        }else {
//            TIMElem *lastElem = [msg getElem:(msg.elemCount-1)];
//
//            if([lastElem isKindOfClass:[TIMTextElem class]]){
//                TIMTextElem *text = (TIMTextElem *)lastElem;
//                //str = text.text;
//                TConversationCellData *data = [[TConversationCellData alloc] init];
//                data.subTitle = text.text;
//                data.unRead = [conv getUnReadMessageNum];
//                data.lastConv = conv;
//                data.head = TUIKitResource(@"default_group");
//                data.convId = [conv getReceiver];
//                data.timestamp = msg.timestamp;
//                data.convType = (TConvType)[conv getType];
//                data.title = data.convId;
//                data.time = [PublicObj getDateDisplayString:msg.timestamp];
//                [rk_m_array addObject:data];
//            }
//            else if([lastElem isKindOfClass:[TIMCustomElem class]]){
//                TIMCustomElem *custom = (TIMCustomElem *)lastElem;
//                //str = custom.ext;
//                NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:custom.data options:NSJSONReadingMutableContainers error:nil];
//                if ([strFormat([jsonDic valueForKey:@"method"]) isEqual:@"sendUserGift"] ||
//                    [strFormat([jsonDic valueForKey:@"method"]) isEqual:@"sendOvoGift"]) {
//                    str = [NSString stringWithFormat:@"[%@]",strFormat([jsonDic valueForKey:@"name"])];
//                }else if ([strFormat([jsonDic valueForKey:@"method"]) isEqual:@"call"]){
//                    str = YZMsg(@"[通话]");
//                }else if([strFormat([jsonDic valueForKey:@"method"]) isEqual:@"GoodsMsg"]){
//                    str = YZMsg(@"[商品]");
//                }
//                else if ([strFormat([jsonDic valueForKey:@"method"]) isEqual:@"follow"]){
//                    NSString *imUid = strFormat([jsonDic valueForKey:@"uid"]);
//                    if ([imUid isEqual:[Config getOwnID]]) {
//                        str = YZMsg(@"你关注了对方，快跟Ta聊聊天吧～");
//                    }else{
//                        str = YZMsg(@"对方已关注你，快跟Ta聊聊天吧～");
//                    }
//                }
//                TConversationCellData *data = [[TConversationCellData alloc] init];
//                data.subTitle = str;
//                data.unRead = [conv getUnReadMessageNum];
//                data.lastConv = conv;
//                data.head = TUIKitResource(@"default_group");
//                data.convId = [conv getReceiver];
//                data.timestamp = msg.timestamp;
//                data.convType = (TConvType)[conv getType];
//                data.title = data.convId;
//                data.time = [PublicObj getDateDisplayString:msg.timestamp];
//                [rk_m_array addObject:data];
//            }
//            else if([lastElem isKindOfClass:[TIMImageElem class]]){
//                str = YZMsg(@"[图片]");
//                TConversationCellData *data = [[TConversationCellData alloc] init];
//                data.subTitle = str;
//                data.unRead = [conv getUnReadMessageNum];
//                data.lastConv = conv;
//                data.head = TUIKitResource(@"default_group");
//                data.convId = [conv getReceiver];
//                data.timestamp = msg.timestamp;
//                data.convType = (TConvType)[conv getType];
//                data.title = data.convId;
//                data.time = [PublicObj getDateDisplayString:msg.timestamp];
//                [rk_m_array addObject:data];
//            }
//            else if([lastElem isKindOfClass:[TIMSoundElem class]]){
//                str = YZMsg(@"[语音]");
//                TConversationCellData *data = [[TConversationCellData alloc] init];
//                data.subTitle = str;
//                data.unRead = [conv getUnReadMessageNum];
//                data.lastConv = conv;
//                data.head = TUIKitResource(@"default_group");
//                data.convId = [conv getReceiver];
//                data.timestamp = msg.timestamp;
//                data.convType = (TConvType)[conv getType];
//                data.title = data.convId;
//                data.time = [PublicObj getDateDisplayString:msg.timestamp];
//                [rk_m_array addObject:data];
//            }
//            else if([lastElem isKindOfClass:[TIMVideoElem class]]){
//                str = YZMsg(@"[视频]");
//                TConversationCellData *data = [[TConversationCellData alloc] init];
//                data.subTitle = str;
//                data.unRead = [conv getUnReadMessageNum];
//                data.lastConv = conv;
//                data.head = TUIKitResource(@"default_group");
//                data.convId = [conv getReceiver];
//                data.timestamp = msg.timestamp;
//                data.convType = (TConvType)[conv getType];
//                data.title = data.convId;
//                data.time = [PublicObj getDateDisplayString:msg.timestamp];
//                [rk_m_array addObject:data];
//            }
//            else if([lastElem isKindOfClass:[TIMFaceElem class]]){
//                str = @"[动画表情]";
//                TConversationCellData *data = [[TConversationCellData alloc] init];
//                data.subTitle = str;
//                data.unRead = [conv getUnReadMessageNum];
//                data.lastConv = conv;
//                data.head = TUIKitResource(@"default_group");
//                data.convId = [conv getReceiver];
//                data.timestamp = msg.timestamp;
//                data.convType = (TConvType)[conv getType];
//                data.title = data.convId;
//                data.time = [PublicObj getDateDisplayString:msg.timestamp];
//                [rk_m_array addObject:data];
//            }
//            else if([lastElem isKindOfClass:[TIMFileElem class]]){
//                str = @"[文件]";
//                TConversationCellData *data = [[TConversationCellData alloc] init];
//                data.subTitle = str;
//                data.unRead = [conv getUnReadMessageNum];
//                data.lastConv = conv;
//                data.head = TUIKitResource(@"default_group");
//                data.convId = [conv getReceiver];
//                data.timestamp = msg.timestamp;
//                data.convType = (TConvType)[conv getType];
//                data.title = data.convId;
//                data.time = [PublicObj getDateDisplayString:msg.timestamp];
//                [rk_m_array addObject:data];
//            }
//            else if([lastElem isKindOfClass:[TIMLocationElem class]]){
//                str = YZMsg(@"[位置]");
//                TConversationCellData *data = [[TConversationCellData alloc] init];
//                data.subTitle = str;
//                data.unRead = [conv getUnReadMessageNum];
//                data.lastConv = conv;
//                data.head = TUIKitResource(@"default_group");
//                data.convId = [conv getReceiver];
//                data.timestamp = msg.timestamp;
//                data.convType = (TConvType)[conv getType];
//                data.title = data.convId;
//                data.time = [PublicObj getDateDisplayString:msg.timestamp];
//                [rk_m_array addObject:data];
//            }
//            else if ([lastElem isKindOfClass:[TIMGroupTipsElem class]]) {
//                TIMGroupTipsElem *tips = (TIMGroupTipsElem *)lastElem;
//                //NSLog(@"xxxxxxx:=====:%@",tips.userList);
//                switch (tips.type) {
//                    case TIM_GROUP_TIPS_TYPE_KICKED: {
//                        NSLog(@"im_tips_kicked:%@===ID:%@",tips.userList,tips.group);
//                        dispatch_group_enter(imListGroup);
//                        dispatch_group_async(imListGroup, group_queue, ^{
//                            [[YBImManager shareInstance] transformInfoWithList:tips.userList finish:^(NSString *transformStr) {
//                                NSString *keckedStr = [NSString stringWithFormat:@"\"%@\"%@",transformStr,YZMsg(@"退出群组")];
//                                TConversationCellData *data = [[TConversationCellData alloc] init];
//                                data.subTitle = keckedStr;
//                                data.unRead = [conv getUnReadMessageNum];
//                                data.lastConv = conv;
//                                data.head = TUIKitResource(@"default_group");
//                                data.convId = [conv getReceiver];
//                                data.timestamp = msg.timestamp;
//                                data.convType = (TConvType)[conv getType];
//                                data.title = data.convId;
//                                data.time = [PublicObj getDateDisplayString:msg.timestamp];
//                                [rk_m_array addObject:data];
//                                dispatch_group_leave(imListGroup);
//                            }];
//                        });
//                    }break;
//                    case TIM_GROUP_TIPS_TYPE_INVITE: {
//                        NSLog(@"im_tips_invite:%@===ID:%@",tips.userList,tips.group);
//                        for (NSString *getStr in tips.userList) {
//                            if ([getStr isEqual:[Config getOwnID]]) {
//                                [[NSNotificationCenter defaultCenter] postNotificationName:ybImConveEvent object:nil userInfo:nil];
//                            }
//                        }
//                        dispatch_group_enter(imListGroup);
//                        dispatch_group_async(imListGroup, group_queue, ^{
//                            [[YBImManager shareInstance] transformInfoWithList:tips.userList finish:^(NSString *transformStr) {
//                                NSString *inviteStr = [NSString stringWithFormat:@"\"%@\"%@",transformStr,YZMsg(@"加入群组")];
//                                TConversationCellData *data = [[TConversationCellData alloc] init];
//                                data.subTitle = inviteStr;
//                                data.unRead = [conv getUnReadMessageNum];
//                                data.lastConv = conv;
//                                data.head = TUIKitResource(@"default_group");
//                                data.convId = [conv getReceiver];
//                                data.timestamp = msg.timestamp;
//                                data.convType = (TConvType)[conv getType];
//                                data.title = data.convId;
//                                data.time = [PublicObj getDateDisplayString:msg.timestamp];
//                                [rk_m_array addObject:data];
//                                dispatch_group_leave(imListGroup);
//                            }];
//                        });
//                    }break;
//                    default:
//                        break;
//                }
//            }else {
//                continue;
//            }
//        }
//    }
//    dispatch_group_notify(imListGroup, group_queue, ^{
//        //NSLog(@"last-finish");
//        if (finish) {
//            finish([rk_m_array mutableCopy]);
//        }
//    });
//}

#pragma mark - 更新腾讯云用户资料
//-(void)updateUserInfoToTxWithParam:(NSDictionary *)param; {
//
//    NSString *yb_age = strFormat([param valueForKey:@"age"]);
//    NSString *yb_avatar = strFormat([param valueForKey:@"avatar"]);
//    NSString *yb_city = strFormat([param valueForKey:@"city"]);
//    NSString *yb_user_nickname = strFormat([param valueForKey:@"user_nickname"]);
//    NSString *yb_sex = strFormat([param valueForKey:@"sex"]);
//    NSString *yb_signature = strFormat([param valueForKey:@"signature"]);
//
//    NSMutableDictionary *userProfileDic = [NSMutableDictionary dictionary];
//
//    NSString *ageKey = [TIMProfileTypeKey_Custom_Prefix stringByAppendingString:IMKey_Custom_Suffix_Age];
//    NSString *avatarKey = [TIMProfileTypeKey_Custom_Prefix stringByAppendingString:IMKey_Custom_Suffix_Avatar];
//    NSString *cityKey = [TIMProfileTypeKey_Custom_Prefix stringByAppendingString:IMKey_Custom_Suffix_City];
//    NSString *nameKey = [TIMProfileTypeKey_Custom_Prefix stringByAppendingString:IMKey_Custom_Suffix_Nickname];
//    NSString *sexKey = [TIMProfileTypeKey_Custom_Prefix stringByAppendingString:IMKey_Custom_Suffix_Sex];
//    NSString *signKey = [TIMProfileTypeKey_Custom_Prefix stringByAppendingString:IMKey_Custom_Suffix_Sign];
//
//    if (![PublicObj checkNull:yb_age]) {
//        [userProfileDic setObject:yb_age forKey:ageKey];
//    }
//    if (![PublicObj checkNull:yb_avatar]) {
//        [userProfileDic setObject:yb_avatar forKey:avatarKey];
//    }
//    if (![PublicObj checkNull:yb_city]) {
//        [userProfileDic setObject:yb_city forKey:cityKey];
//    }
//    if (![PublicObj checkNull:yb_user_nickname]) {
//        [userProfileDic setObject:yb_user_nickname forKey:nameKey];
//    }
//    if (![PublicObj checkNull:yb_sex]) {
//        [userProfileDic setObject:yb_sex forKey:sexKey];
//    }
//    if (![PublicObj checkNull:yb_signature]) {
//        [userProfileDic setObject:yb_signature forKey:signKey];
//    }
//    if ([userProfileDic allKeys].count<=0) {
//        return;
//    }
//    TIMFriendshipManager *imProfile = [TIMFriendshipManager sharedInstance];
//    int isOk = [imProfile modifySelfProfile:[userProfileDic mutableCopy] succ:^{
//        //NSLog(@"im_update_user_suc:%@",userProfileDic);
//    } fail:^(int code, NSString *msg) {
//        NSLog(@"im_update_user_fail:%d-msg:%@",code,msg);
//    }];
//    NSLog(@"im_update_user_isOK:%d",isOk);
//
//}

#pragma mark - 获取加入的群组
//-(void)getJoinGroupList:(ImGroupListBlock)imGroupList; {
//    TIMGroupManager *groupManager = [TIMGroupManager sharedInstance];
//    int isOk = [groupManager getGroupList:^(NSArray *groupList) {
//        if (imGroupList) {
//            imGroupList(groupList);
//        }
//    } fail:^(int code, NSString *msg) {
//        if (imGroupList) {
//            imGroupList(@[]);
//        }
//    }];
//    if (isOk != 0 && imGroupList) {
//        imGroupList(@[]);
//    }
//}

#pragma mark - 群消息转换
//-(void)transformInfoWithList:(NSArray *)list finish:(ImTransformBlock)finish {
//    NSString *transformStr = @"";
//    TIMFriendshipManager *imProfile = [TIMFriendshipManager sharedInstance];
//    int isOk = [imProfile getUsersProfile:list forceUpdate:YES succ:^(NSArray<TIMUserProfile *> *profiles) {
//        NSMutableArray *m_array = [NSMutableArray array];
//        for (TIMUserProfile * profile in profiles) {
//            NSString *nameStr = [PublicObj transformToStringWithData:[profile.customInfo valueForKey:IMKey_Custom_Suffix_Nickname]];
//            [m_array addObject:nameStr];
//        }
//        NSString *users = [m_array componentsJoinedByString:@"、"];
//        if (finish) {
//            finish(users);
//        }
//    } fail:^(int code, NSString *msg) {
//        if (finish) {
//            finish(transformStr);
//        }
//    }];
//    if (isOk != 0 && finish) {
//        finish(transformStr);
//    }
//}
-(TConversationCellData *)createEmptyCellDataWithId:(NSString *)convid {
    TConversationCellData *data = [[TConversationCellData alloc] init];
    data.subTitle = @"";
    data.unRead = 0;
//    data.lastConv = nil;
    data.head = TUIKitResource(@"default_group");
    data.convId = convid;
    data.timestamp = [NSDate date];
    data.convType = TConv_Type_C2C;
    data.title = data.convId;
    data.time = [PublicObj getDateDisplayString:data.timestamp];
    return data;
}
//-(void)clearUnreadConvId:(NSString *)convid sendNot:(BOOL)send{
//    TIMConversation *conv = [[TIMManager sharedInstance] getConversation:TIM_C2C receiver:convid];
//    [conv setReadMessage:nil succ:^{
//        NSLog(@"rk_clear_suc");
//    } fail:^(int code, NSString *msg) {
//        NSLog(@"rk_clear_fail");
//    }];
//    if (send) {
//        [[NSNotificationCenter defaultCenter] postNotificationName:TUIKitNotification_TIMCancelunread object:nil];
//    }
//}
//-(void)sendClearNot {
//    [[NSNotificationCenter defaultCenter] postNotificationName:TUIKitNotification_TIMCancelunread object:nil];
//}
@end







































/*
 #pragma mark - 获取最后一条消息 02
- (void)getLastDisplayString:(TIMConversation *)conv finish:(ImTransformBlock)finish;{
    if (!finish) {
        return;
    }
    NSString *str = @"";
    TIMMessageDraft *draft = [conv getDraft];
    TIMMessage *msg = [conv getLastMsg];
    if(draft && draft.elemCount>0){
        TIMElem *draftElem = [draft getElem:(draft.elemCount-1)];
        if([draftElem isKindOfClass:[TIMTextElem class]]){
            TIMTextElem *text = (TIMTextElem *)draftElem;
            str = [NSString stringWithFormat:@"[%@]%@", YZMsg(@"草稿"),text.text];
            finish(str);
        } else{
            finish(@"no msg");
        }
        ///return str;
    }else if(msg.status == TIM_MSG_STATUS_LOCAL_REVOKED){
        if(msg.isSelf || [[msg getConversation] getType] == TIM_C2C){
            //return YZMsg(@"你撤回了一条消息");
            NSString *revokedStr = msg.isSelf ? YZMsg(@"你撤回了一条消息"):YZMsg(@"对方撤回了一条消息");
            finish(revokedStr);
        } else if([[msg getConversation] getType] == TIM_GROUP){
            //return YZMsg(@"对方撤回了一条消息");
            TIMFriendshipManager *imProfile = [TIMFriendshipManager sharedInstance];
            int revokedOk = [imProfile getUsersProfile:@[msg.sender] forceUpdate:YES succ:^(NSArray<TIMUserProfile *> *profiles) {
                TIMUserProfile * profile = [profiles lastObject];
                NSString *nameStr = [PublicObj transformToStringWithData:[profile.customInfo valueForKey:IMKey_Custom_Suffix_Nickname]];
                NSString *revokedStr = [NSString stringWithFormat:@"\"%@\"%@",nameStr,YZMsg(@"撤回了一条消息")];
                
//                NSDictionary *notDic = @{@"type":@"1",
//                                         @"groupid":[msg getConversation].getReceiver,
//                                         @"showStr":revokedStr,
//                };
//                [[NSNotificationCenter defaultCenter] postNotificationName:ybImConveEvent object:nil userInfo:notDic];
                
                finish(revokedStr);
            } fail:^(int code, NSString *msg) {
                finish(@"getlast fail");
            }];
            if (revokedOk != 0) {
                finish(@"getlast fail code");
            }
        }else {
            finish(@"getlast fail type");
        }
    }else {
        TIMElem *lastElem = [msg getElem:(msg.elemCount-1)];
        
        if([lastElem isKindOfClass:[TIMTextElem class]]){
            TIMTextElem *text = (TIMTextElem *)lastElem;
            str = text.text;
            if (finish) {
                finish(str);
            }
        }
        else if([lastElem isKindOfClass:[TIMCustomElem class]]){
            TIMCustomElem *custom = (TIMCustomElem *)lastElem;
            //str = custom.ext;
            NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:custom.data options:NSJSONReadingMutableContainers error:nil];
            if ([strFormat([jsonDic valueForKey:@"method"]) isEqual:@"sendUserGift"] ||
                [strFormat([jsonDic valueForKey:@"method"]) isEqual:@"sendOvoGift"]) {
                str = [NSString stringWithFormat:@"[%@]",strFormat([jsonDic valueForKey:@"name"])];
            }else if ([strFormat([jsonDic valueForKey:@"method"]) isEqual:@"call"]){
                str = YZMsg(@"[通话]");
            }
            finish(str);
        }
        else if([lastElem isKindOfClass:[TIMImageElem class]]){
            str = YZMsg(@"[图片]");
            finish(str);
        }
        else if([lastElem isKindOfClass:[TIMSoundElem class]]){
            str = YZMsg(@"[语音]");
            finish(str);
        }
        else if([lastElem isKindOfClass:[TIMVideoElem class]]){
            str = YZMsg(@"[视频]");
            finish(str);
        }
        else if([lastElem isKindOfClass:[TIMFaceElem class]]){
            str = @"[动画表情]";
            finish(str);
        }
        else if([lastElem isKindOfClass:[TIMFileElem class]]){
            str = @"[文件]";
            finish(str);
        }else if ([lastElem isKindOfClass:[TIMGroupTipsElem class]]) {
            TIMGroupTipsElem *tips = (TIMGroupTipsElem *)lastElem;
            //NSLog(@"xxxxxxx:=====:%@",tips.userList);
            switch (tips.type) {
                case TIM_GROUP_TIPS_TYPE_KICKED: {
                    NSLog(@"im_tips_kicked:%@===ID:%@",tips.userList,tips.group);
                    [[YBImManager shareInstance] transformInfoWithList:tips.userList finish:^(NSString *transformStr) {
                        NSString *keckedStr = [NSString stringWithFormat:@"\"%@\"%@",transformStr,YZMsg(@"退出群组")];
                        
//                        NSDictionary *notDic = @{@"type":@"1",
//                                                 @"groupid":[msg getConversation].getReceiver,
//                                                 @"showStr":keckedStr,
//                        };
//                        [[NSNotificationCenter defaultCenter] postNotificationName:ybImConveEvent object:nil userInfo:notDic];
                        
                        finish(keckedStr);
                    }];
                }break;
                case TIM_GROUP_TIPS_TYPE_INVITE: {
                    NSLog(@"im_tips_invite:%@===ID:%@",tips.userList,tips.group);
                    [[YBImManager shareInstance] transformInfoWithList:tips.userList finish:^(NSString *transformStr) {
                        NSString *inviteStr = [NSString stringWithFormat:@"\"%@\"%@",transformStr,YZMsg(@"加入群组")];
                        
//                        NSDictionary *notDic = @{@"type":@"1",
//                                                 @"groupid":[msg getConversation].getReceiver,
//                                                 @"showStr":inviteStr,
//                        };
//                        [[NSNotificationCenter defaultCenter] postNotificationName:ybImConveEvent object:nil userInfo:notDic];
                        
                        for (NSString *getStr in tips.userList) {
                            if ([getStr isEqual:[Config getOwnID]]) {
                                [[NSNotificationCenter defaultCenter] postNotificationName:ybImConveEvent object:nil userInfo:nil];
                            }
                        }
                        finish(inviteStr);
                    }];
                }break;
                default:{
                    finish(@"no last");
                }break;
            }
        }else {
            finish(@"no last");
        }
    }
}
*/


/*
#pragma mark - 获取最后一条消息 01
- (NSString *)getLastDisplayString:(TIMConversation *)conv{
    NSString *str = @"";
    TIMMessageDraft *draft = [conv getDraft];
    if(draft){
        for (int i = 0; i < draft.elemCount; ++i) {
            TIMElem *elem = [draft getElem:i];
            if([elem isKindOfClass:[TIMTextElem class]]){
                TIMTextElem *text = (TIMTextElem *)elem;
                str = [NSString stringWithFormat:@"[%@]%@", YZMsg(@"草稿"),text.text];
                break;
            } else{
                continue;
            }
        }
        return str;
    }
    
    TIMMessage *msg = [conv getLastMsg];
    if(msg.status == TIM_MSG_STATUS_LOCAL_REVOKED){
        if(msg.isSelf){
            return YZMsg(@"你撤回了一条消息");
        } else{
            return YZMsg(@"对方撤回了一条消息");
        }
    }
    for (int i = 0; i < msg.elemCount; ++i) {
        TIMElem *elem = [msg getElem:i];
        if([elem isKindOfClass:[TIMTextElem class]]){
            TIMTextElem *text = (TIMTextElem *)elem;
            str = text.text;
            break;
        }
        else if([elem isKindOfClass:[TIMCustomElem class]]){
            TIMCustomElem *custom = (TIMCustomElem *)elem;
            //str = custom.ext;
            NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:custom.data options:NSJSONReadingMutableContainers error:nil];
            if ([strFormat([jsonDic valueForKey:@"method"]) isEqual:@"sendUserGift"] ||
                [strFormat([jsonDic valueForKey:@"method"]) isEqual:@"sendOvoGift"]) {
                str = [NSString stringWithFormat:@"[%@]",strFormat([jsonDic valueForKey:@"name"])];
            }else if ([strFormat([jsonDic valueForKey:@"method"]) isEqual:@"call"]){
                str = YZMsg(@"[通话]");
            }
            break;
        }
        else if([elem isKindOfClass:[TIMImageElem class]]){
            str = YZMsg(@"[图片]");
            break;
        }
        else if([elem isKindOfClass:[TIMSoundElem class]]){
            str = YZMsg(@"[语音]");
            break;
        }
        else if([elem isKindOfClass:[TIMVideoElem class]]){
            str = YZMsg(@"[视频]");
            break;
        }
        else if([elem isKindOfClass:[TIMFaceElem class]]){
            str = @"[动画表情]";
            break;
        }
        else if([elem isKindOfClass:[TIMFileElem class]]){
            str = @"[文件]";
            break;
        }
        
        //else if([elem isKindOfClass:[TIMGroupSystemElem class]]){
        //    TIMGroupSystemElem *custom = (TIMGroupSystemElem *)elem;
        //    NSLog(@"last_im_group:=======%ld",(long)custom.type);
        //}
        else if([elem isKindOfClass:[TIMGroupTipsElem class]]){
            TIMGroupTipsElem *tips = (TIMGroupTipsElem *)elem;
            NSLog(@"xxxxcccccc:%ld",(long)tips.type);
            switch (tips.type) {
                case TIM_GROUP_TIPS_TYPE_INFO_CHANGE: {
                    for (TIMGroupTipsElemGroupInfo *info in tips.groupChangeList) {
                        switch (info.type) {
                            case TIM_GROUP_INFO_CHANGE_GROUP_NAME: {
                                str = [NSString stringWithFormat:@"\"%@\"修改群名为\"%@\"", tips.opUser, info.value];
                            } break;
                            case TIM_GROUP_INFO_CHANGE_GROUP_INTRODUCTION: {
                                str = [NSString stringWithFormat:@"\"%@\"修改群简介为\"%@\"", tips.opUser, info.value];
                            }break;
                            case TIM_GROUP_INFO_CHANGE_GROUP_NOTIFICATION: {
                                str = [NSString stringWithFormat:@"\"%@\"修改群公告为\"%@\"", tips.opUser, info.value];
                            } break;
                            case TIM_GROUP_INFO_CHANGE_GROUP_OWNER: {
                                str = [NSString stringWithFormat:@"\"%@\"修改群主为\"%@\"", tips.opUser, info.value];
                            } break;
                            default:
                                break;
                        }
                    }
                } break;
                case TIM_GROUP_TIPS_TYPE_KICKED: {
                    NSString *users = [tips.userList componentsJoinedByString:@"、"];
                    str = [NSString stringWithFormat:@"\"%@\"将\"%@\"剔出群组", tips.opUser, users];
                }break;
                case TIM_GROUP_TIPS_TYPE_INVITE: {
                    NSString *users = [tips.userList componentsJoinedByString:@"、"];
                    str = [NSString stringWithFormat:@"\"%@\"邀请\"%@\"加入群组", tips.opUser, users];
                }break;
                default:
                    break;
            }
        }else{
            continue;
        }
    }
    return str;
}
*/
